from math import sqrt
import commands
import sys


#MAIN

# create file names
input_file = sys.argv[1]
file_inp  = input_file + '.inp'
file_mesh = input_file + '.mesh'

# remove all commas in the inp file and remove previous mesh file
command_remove_commas = 'sed -e \'s/,/ /g\' ' + file_inp + ' > tttt.mesh && mv tttt.mesh ' + file_inp 
commands.getoutput(command_remove_commas)
command_remove_old_mesh = 'rm ' + file_mesh
commands.getoutput(command_remove_old_mesh)

# open both files
log_inp  = open (file_inp,  'r')
log_mesh = open (file_mesh, 'a')

# find the beginning of the node list
lin = log_inp.readline ()
lst = lin.split ()
while lst[0] != '*NODE': 
    lin = log_inp.readline ()
    lst = lin.split ()
lin  = log_inp.readline ()
lst  = lin.split ()

# read inp file until end of node list and print mesh file
log_mesh.write("<Nodes>\n")
while lst[0] != '**': 
    log_mesh.write(str(int(lst[0])-1))
    log_mesh.write("\t")
    for i in range (1, len(lst)):
    	log_mesh.write(lst[i])
    	log_mesh.write("\t")
    log_mesh.write(";\n")
    lin = log_inp.readline ()
    lst = lin.split ()
log_mesh.write("</Nodes>\n\n<Elements>\n")

# find the beginning of the element list
lin = log_inp.readline ()
lst = lin.split ()
while lst[0] != '*ELEMENT': 
    lin = log_inp.readline ()
    lst = lin.split ()
lin = log_inp.readline ()
lst = lin.split ()

# read inp file until end of node list and print mesh file
while lst[0] != '**': 
    log_mesh.write(str(int(lst[0])-1))
    log_mesh.write("\t")
    for i in range (1, len(lst)):
      log_mesh.write(str(int(lst[i])-1))
      log_mesh.write("\t")
    log_mesh.write(";\n")
    lin = log_inp.readline ()
    lst = lin.split ()
log_mesh.write("</Elements>\n\n")

# read inp file until end of node list and print mesh file
lin = log_inp.readline ()
lst = lin.split ()
while lst[0] != '*END': 
    if lst[0] == "*NSET" :
      log_mesh.write("<NodeGroup name=\"")
      log_mesh.write(lin[12:len(lin)-1])
      log_mesh.write("\">\n{")
      lin = log_inp.readline ()
      lst = lin.split ()
      count = 0
      while lst[0].isdigit ():
        if count != 0 :
          log_mesh.write(",\t")
        for i in range (0, len(lst)):
          log_mesh.write(str(int(lst[i])-1))
          if i != len(lst)-1 :
            log_mesh.write(",\t")
        lin = log_inp.readline ()
        lst = lin.split ()
	count = 1
      log_mesh.write("}\n</NodeGroup>\n\n")
    if lst[0] != "*NSET" :
      lin = log_inp.readline ()
      lst = lin.split ()
   

# close files
log_mesh.close ()
log_inp.close ()

